<?php

if(!defined('IN_ADAGPS'))
{
    die(SYSTEM_ACCESS_DENIED);
}
$objXajax->registerFunction('fmfrmmanager_loadMenu');      
$objXajax->registerFunction('fmfrmmanager_loadGrid');      
$objXajax->registerFunction('fmfrmmanager_checkedRoom');

$objXajax->registerFunction('fmfrmmanager_addRemoveProduct');
$objXajax->registerFunction('fmfrmmanager_moveRoom');
$objXajax->registerFunction('fmfrmmanager_loadProduct');
$objXajax->registerFunction('fmfrmmanager_finishRoom');
$objXajax->registerFunction('fmfrmmanager_closeRoom');

$objXajax->registerFunction('fmfrmmanager_addNewProduct');
$objXajax->registerFunction('fmfrmmanager_undo');
$objXajax->registerFunction('fmfrmmanager_loadRoom');
$objXajax->registerFunction('fmfrmmanager_showBill');
$objXajax->registerFunction('fmfrmmanager_save');
$objXajax->registerFunction('fmfrmmanager_init');
$objXajax->registerFunction('fmmanager_deleteproduct');
$objXajax->registerFunction('fmfrmmanager_mergeRoom');

/*
* ham dung cho left menu
* 
*/
//global $fmpromotype;

function fmfrmmanager_init(){
    global $objDbSelect,$lang,$arrMenu,$arrdetail,$hotel_id;
    $objResponse = new xajaxResponse();
    
    $sql= "select fm_print,fm_greeting_bill ,fm_name_service,fm_start_bill ,fm_cancelbtn,fm_undobtn,fm_undotime,fm_column,fm_percent_promotion from cus_config WHERE service_id = '$hotel_id'";    
     
    $arr= $objDbSelect->GetArray($sql);
    $showprintbtn=$arr[0]['fm_print'] ;
    $fm_cancelbtn=$arr[0]['fm_cancelbtn'] ;
    $fm_undobtn=$arr[0]['fm_undobtn'] ;
    $fm_undotime=$arr[0]['fm_undotime'] ;
    $fm_percent=$arr[0]['fm_percent_promotion'] ;
    //echo '<pre>'; print_r($arr); die();
    $fm_greeting_bill=addslashes($arr[0]['fm_greeting_bill']) ;
    $fm_start_bill    = addslashes($arr[0]['fm_start_bill']) ;
    $fm_name_service  = addslashes($arr[0]['fm_name_service']) ;
    
    $fm_column=$arr[0]['fm_column'] ;
    if($_SESSION['current']['power_type_id']==POWER_CUSTOMER){
       $fm_cancelbtn =1;                                                                           
       $fm_undobtn=1;  
    }
    $objResponse->addScript("fm_obj.assignConfig($showprintbtn,'$fm_greeting_bill',$fm_cancelbtn,
    $fm_undobtn,$fm_undotime,$fm_percent,'$fm_start_bill','$fm_name_service');");   
    
    $objResponse->addScript("xajax_fmfrmmanager_loadGrid('$fm_column');");                       
                           
    return $objResponse->getXML();
}

function fmfrmmanager_loadMenu(){     

    global $lang,$arrMenu,$arrdetail;
    $objResponse = new xajaxResponse();
    $arr = array();
    $arrdetail= array();
    $arrMain = common_getMenu($arr,$arrdetail);
    $oTbs = new clsTinyButStrong();
    $oTbs ->LoadTemplate("templates/$lang/customer/fm_manager_menu_grid.html");
    $oTbs->MergeBlock('blk_list', $arrMain);
    $oTbs->MergeBlock('blk_list1', 'array', 'arrdetail[%p1%]');
        
    $objResponse->addAssign('fmfrmmanager_leftmenu', 'innerHTML', $oTbs->Source);
     
    $count = count($arr);
    for($i=0;$i<$count;$i++){ // 
        $name     = $arr[$i]['name'];
        $price    = $arr[$i]['price'];
        $id       = $arr[$i]['id'];
        $unit     = $arr[$i]['unit'];
        $unitname = $arr[$i]['unitname'];
        $area_ext = $arr[$i]['area_ext'];
        $objResponse->addScript("fm_obj.createAssignProductPrice($id,'$name','$price','$unit','$unitname',$area_ext);"); 
    }
    $indexNewProduct = time();
    $objResponse->addScript("fm_obj.indexNewProduct=$indexNewProduct;");
    $objResponse->addScript("fmfrmmanager_dropdrapmenu();");  
    $objResponse->addScript("changeWaiting(1);");  
                          
    return $objResponse->getXML();
}

function fmfrmmanager_loadRoom(){ 
    global $lang,$arrDetail,$objDbSelect;
        $objResponse = new xajaxResponse();// dong luon luon co khi goi ham ajax
        $arrDetail = fmfrmmanager_getRoomInit();
         
        for($i=0;$i<count($arrDetail);$i++){
            $id = $arrDetail[$i]['id'];
            $name = $arrDetail[$i]['name'];
            $type = $arrDetail[$i]['type_id'];            
            $extprice= $arrDetail[$i]['extprice'];
            $objResponse->addScript("fm_obj.createAssignRoomObj($id,'$name','$type','$extprice'"); 
        }

    return $objResponse->getXML(); // dong luon luon co khi goi ham ajax   
}

function fmfrmmanager_loadGrid($col){     

    global $lang,$arrMenu,$arrDetail,$hotel_id,$objDbSelect;
    $objResponse = new xajaxResponse();
    $arrDetail = array();
    $arrRoom = fmfrmmanager_getRoom($arrDetail,$arr);
        
     for($i=0;$i<count($arr);$i++){
            $id = $arr[$i]['id'];
            $name = $arr[$i]['name'];
            $type = $arr[$i]['type_id'];            
            $extprice= $arr[$i]['extprice'];
            $objResponse->addScript("fm_obj.createAssignRoomObj($id,'$name','$type','$extprice')"); 
       }  
        
        

    $oTbs = new clsTinyButStrong();    
    $oTbs->LoadTemplate('templates/'.$lang."/customer/fm_manager_grid_$col.html");   
    $oTbs->MergeBlock('blk_total', $arrRoom); 
    
    $oTbs->MergeBlock('blk_data', 'array', 'arrDetail[%p1%]'); 
    

    $oTbs->Show(TBS_NOTHING);
    $objResponse->addAssign('fmfrmmanager_divGrid', 'innerHTML', $oTbs->Source);
    $objResponse->addScript("addJsContext();");  
     
   $objResponse->addScript('$(".clsbtn_fm").button();');          
   $objResponse->addScript('$(".fm_chkHide").button();');          
   $objResponse->addScript('xajax_fmfrmmanager_loadMenu();'); 
   $objResponse->addScript("setTimeout('fmfrmmanager_firstload()',2000);");           
   $objResponse->addScriptCall("fmfrmmanager_checkundobtn();");
             
    return $objResponse->getXML(); // dong luon luon co khi goi ham ajax   
}

function  fmfrmmanager_getRoom(&$arrDetail,&$arr){
    global $objDbSelect,$tbl_postfix,$hotel_id;      
    $arrResult = array();
    $sqlSelect = "SELECT r.id,r.room_type,r.name,t.style as color,t.name  as name_type,t.id as type_id ,t.extprice
    FROM fm_room as r join fm_room_type  as t on r.room_type=t.id and t.service_id = $hotel_id where r.active = 1 and t.active = 1
     order by r.room_type,r.name";
    $arr =  $objDbSelect->GetArray($sqlSelect);
    for($i=0;$i<count($arr);$i++){
        $type_id = $arr[$i]['type_id'];
        $arrResult[$type_id]= array('type_id'=>$arr[$i]['type_id'],'name_type'=>$arr[$i]['name_type']);
        $arrDetail[$type_id][]=array('id'=>$arr[$i]['id'],'color'=>$arr[$i]['color'],'name'=>$arr[$i]['name']);
    }
    return $arrResult;
}
/*
* 
*/
function  fmfrmmanager_getRoomInit(){
    global $objDbSelect,$tbl_postfix,$hotel_id;
    $arrResult = array();
    $sqlSelect = "SELECT r.id,r.name as name,r.room_type,t.extprice,t.style ,t.name  as name_type,t.id as type_id
    FROM fm_room as r join fm_room_type  as t on r.room_type=t.id  and t.service_id = $hotel_id join cus_config cf on 
    cf.service_id = $hotel_id where r.active = 1  order by r.room_type,r.name";
    $arr =  $objDbSelect->GetArray($sqlSelect);
    return $arr;
}   

function fmfrmmanager_addRemoveProduct($arrAddRemove,$arrProduct=''){
     global $lang,$arrMenu,$objDbSelect;
     $objResponse = new xajaxResponse();
         for($i=0;$i<count($arrAddRemove);$i++){
             $temp = $arrAddRemove[$i];
             $arrId = explode(';',$temp);
             $room_id = $arrId[0];
             $product_id = $arrId[1];
             $area_exprice = $arrId[2];
             $nump = $arrId[3];
             $flg = fmfrmmanager_actionDB($room_id,$product_id,$nump,$arrProduct,$area_exprice) ;
             if(!$flg){
                 $objResponse->addScript("fmfrmmanager_reloadform('Sản phẩm vừa xóa không có trên bàn!');");   //09
             }
         }                                                                    

     return $objResponse->getXML();    
}

function fmfrmmanager_actionDB($table_id,$product_id,$nump,$arrProduct,$area_extprice){
  global $objDbSelect,$tbl_postfix,$user_id;
  //$service_type =  SVT_FILM;
  
  if($nump<0){
      
      $sqlSelect = "select id,num,area_extprice,date_created from cus_history_product$tbl_postfix where table_id =  
     '$table_id' and product_id = '$product_id'  and flg=0 and num <>0 order by date_created desc";
     $arrSelect = $objDbSelect->GetArray($sqlSelect);
     $sql =''; 
     if(is_array($arrSelect) && count($arrSelect)>0){
         for($i=0;$i<count($arrSelect);$i++){
             $curnum =  $arrSelect[$i]['num'];//
             $id =  $arrSelect[$i]['id'];//
             $nump += $curnum ;
             if($nump<1){
                 $sql= "delete from cus_history_product$tbl_postfix where id  = $id ";  
                 $objDbSelect->Execute($sql); 
                 if($nump==0) break;
         // write log........................
             }else{
                $sql = "update cus_history_product$tbl_postfix SET num = '$nump' where id  = $id ";
                $objDbSelect->Execute($sql);
                 if($nump>0) break;
          // write log........................ 
             }
          }

     }else{
         return false;
     }
      
  }else{
      $sqlSelect = "select id,num from cus_history_product$tbl_postfix where table_id =  
     '$table_id' and product_id = '$product_id'  and flg=0 and num <>0 
     and area_extprice='$area_extprice' ";  
     $arrSelect = $objDbSelect->GetArray($sqlSelect);
     if(is_array($arrSelect) && count($arrSelect)>0){ 
         $nump +=  $arrSelect[0]['num'];
         $id =  $arrSelect[0]['id'];
          $sql = "update cus_history_product$tbl_postfix SET num = '$nump' where id  = $id ";
          $objDbSelect->Execute($sql);
     }else{
        $name = $arrProduct[$product_id]['name'];
        $price = $arrProduct[$product_id]['price'];
        $sql = "insert into cus_history_product$tbl_postfix(table_id,product_id,name,price,date_created
        ,user_created,num,flg,first_table_id,area_extprice) 
        values('$table_id','$product_id','$name','$price',now(),'$user_id','$nump',0,'$table_id','$area_extprice')"; 
        $objDbSelect->Execute($sql); 
     }
  } 
  
      
     return true;
}

function fmfrmmanager_moveRoom($RoomFrom,$RoomTo){
    global $objDbSelect,$tbl_postfix,$user_id;
    $objResponse = new xajaxResponse();
    $update = ''; 
    //$service_type = SVT_FILM;
    $sql = "select id from cus_history_product$tbl_postfix where table_id = '$RoomTo' and flg = 0 ";
    $arrcheck = $objDbSelect->GetArray($sql);
    if(is_array($arrcheck)&&count($arrcheck)>0){
        $objResponse->addScript("fmfrmmanager_reloadform('Bàn chuyển đến không còn trống');");
    }else{
       $sqlProduct = "update cus_history_product$tbl_postfix set table_id = '$RoomTo' where table_id = '$RoomFrom' and flg = 0 ";
       $objDbSelect->Execute($sqlProduct); 
    }
     
    return $objResponse->getXML();  
}
/*
* HÃ m nÃ y dÃ¹ng Ä‘á»ƒ load product lÃªn cÃ¡c bÃ n 
* 
* 
*/
function fmfrmmanager_loadProduct($table_id=''){
    global $objDbSelect,$tbl_postfix;
     $objResponse = new xajaxResponse();
     //$service_type =  SVT_FILM;
     $condition =  $table_id==''?'':" and table_id= '$table_id' " ;
    $sql = "select p.name,(p.price+p.area_extprice) as price,sum(p.num) as num,p.product_id,p.table_id as room_id,p.type_pro  from cus_history_product$tbl_postfix as p 
where p.num>0 and p.flg = 0 $condition group by p.product_id,table_id,area_extprice order by p.table_id, p.type_pro, p.date_created"; // lấy sản phẩm trên bàn từ DB
    $arr = $objDbSelect->GetArray($sql);
    //echo $sql; die();
    for($i=0;$i<count($arr);$i++){
        $room_id = $arr[$i]['room_id'];
        $name = addslashes($arr[$i]['name']);
        $num = $arr[$i]['num'];
        $price = $arr[$i]['price'];
        $product_id = $arr[$i]['product_id'];
        $type_pro = $arr[$i]['type_pro'];
        $objResponse->addScript("fmfrmmanager_loadProduct('$room_id','$product_id','$name','$num','$price','$type_pro');"); 
    }
     $objResponse->addScript("fm_addJsContext();"); 
   return $objResponse->getXML();  
}
/*
* hÃ m nÃ y dÃ¹ng Ä‘á»ƒ tÃ­nh toÃ¡n khi khÃ¡ch hÃ n kÃªu tÃ­nh tiá»?n  
* @room_id : id cá»§a bÃ n cáº§n tÃ­nh 
* $current_id : id Ä‘i cá»§a bÃ n mÆ°á»›n hiá»‡n hÃ nh
* $pricehour : tiá»?n giá»?
* $pricetotal : toÃ n bá»™ tiá»?n cá»§a phÃ²ng
*/
function fmfrmmanager_finishRoom($arrPriceSave,$arrConfig){    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $bill_id = $arrPriceSave['bill_id'];
    $room_id = $arrPriceSave['room_id'];  
    $fm_percent = $arrConfig['fm_percent'];
    //echo '<pre>'; print_r($arrPriceSave);  die();
    $sql = " update cus_history_product$tbl_postfix SET flg = 1,general_id = '$bill_id',date_update = now(),user_update =$user_id,
    promotion ='$fm_percent'  where table_id = $room_id and flg = 0 ";
   // echo $sql; die(); 
    if($objDbSelect->Execute($sql)){
        $objResponse->addScript("$('#fmfrmmanager_divprint').dialog('close');");
        $objResponse->addScript("fm_obj.resetRoom($room_id);");
        $objResponse->addScript("$('#fmfrmmanager_div_$room_id').find('.trProduct').remove();");
    }
    $objResponse->addScript("fm_calActiveTableByTableType();");
    return $objResponse->getXML();
}
/*
* HÃ m nÃ y dÃ¹ng Ä‘á»ƒ add sáº£n pháº©m ngoÃ i doanh má»¥c 
* $proId : láº¥y id tá»« indexproduct
* $hdtRoom : id cá»§a bÃ n thÃªm sáº£n pháº©m má»›i
* $name : tÃªn sáº£n pháº©m 
* $price : giÃ¡ cá»§a sáº£n pháº©m ngoÃ i doanh má»¥c
*/
function fmfrmmanager_addNewProduct($proId,$hdRoom,$name,$price,$type,$general_id=''){
    global $objDbSelect,$user_id,$hotel_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sql =''; 
    $name = strip_tags($name);
    $name = addslashes($name);
    $sql = " insert into cus_history_product$tbl_postfix(product_id,name,price,date_created,user_created,num,table_id,type_pro) 
             values('$proId','$name','$price',now(),'$user_id',1,'$hdRoom',$type)";  
    $objDbSelect->Execute($sql);
    return $objResponse->getXML();    
}

function fmfrmmanager_undo($room_id,$undotime){
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
   // $service_type = SVT_FILM;
/*    $sqlcheck = "select count(id) as cnt from fm_current_book$tbl_postfix where room_id = $room_id and flgcal=0 and flg_cancel = 0 ";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    if($arrChk[0]['cnt']==0){ */
    $sqlcheck = "select count(id) as cnt from cus_history_product$tbl_postfix where table_id = $room_id and flg=0 ";
    //echo $sqlcheck; die(); 
    $arrChk=$objDbSelect->GetArray($sqlcheck);
       if($arrChk[0]['cnt']==0){
           $sqlgeneral = "select TIMESTAMPDIFF(MINUTE,p.date_update ,now()) as period,general_id
            from cus_history_product$tbl_postfix as p where p.num>0 and 
            general_id = (select max(f.general_id) from cus_history_product$tbl_postfix f where f.table_id = $room_id and f.flg=1)
             group by p.product_id,table_id,area_extprice order by p.table_id, p.type_pro, p.date_created ";
             //echo $sqlgeneral; die();
            $arrgeneral = $objDbSelect->GetArray($sqlgeneral);
            if(is_array($arrgeneral) && count($arrgeneral)>0 ){
                $period = (int)$arrgeneral[0]['period'];
            if($period>$undotime){
               $objResponse->addScript("alert('Quá thời gian cho phép phục hồi');");  
               $objResponse->addScript("$(fmfrmmanager_undo-$room_id).hide()");  
            }else{
                $general_id =$arrgeneral[0]['general_id']; 
                $sqlupdate= "update cus_history_product$tbl_postfix set flg=0 , promotion = 0 where general_id = $general_id ";
                if($objDbSelect->Execute($sqlupdate)){
                   $objResponse->addScript("xajax_fmfrmmanager_loadProduct($room_id)"); 
                } 
                     
            }
                
        }else{
           $objResponse->addScript("alert('Không có dữ liệu để phục hồi!');"); 
           $objResponse->addScript("$(fmfrmmanager_undo-$room_id).hide()");  
        }
           
       }else{
          $objResponse->addScript("fmfrmmanager_reloadform('Hiện tại bàn này đang có khách!');");  
       }
           

    return $objResponse->getXML();    
}  

function fmfrmmanager_showBill($Room_id,$arrConfig){ 
    global $objDbSelect,$user_id,$tbl_postfix,$total,$lang,$roomname,$promo_value,$bill_date,$bill_id;
   $objResponse = new xajaxResponse();
   
    $sql="SELECT  name, sum(num) as num, sum((price + area_extprice) *  num) as total,0 as style,DATE_FORMAT(now(),'%d/%m/%Y %H:%i') as 
    bill_date,id as bill_id FROM cus_history_product$tbl_postfix where table_id = '$Room_id' and flg = 0 and num >0 group by product_id,area_extprice order by date_created ";
    //echo $sql; die();
    
    $arr = $objDbSelect->GetArray($sql);
     $count = count($arr);
    if($count==0){
        $objResponse->addScript("fmfrmmanager_reloadform('Bàn đã tính tiền rồi!');");
         return $objResponse->getXML();
    }
    for($i=0;$i<$count;$i++){
        $total += (int)$arr[$i]['total']; 
        $total = round($total,-3);
    }
    $promo_value = 0;
    $bill_date = $arr[0]['bill_date'];
    $bill_idtemp = $arr[0]['bill_id']; 
    $bill_id = str_pad($bill_idtemp, 7, '0', STR_PAD_LEFT); 
    //echo $bill_id; die();
    if($arrConfig['fm_percent']!=0){
        $promo_value =-round($total*$arrConfig['fm_percent']/100,-3);
        $total += $promo_value; 
    }
   
    $bill = 'fm_manager_bill_1.html';
    $showbutton=$arrConfig['showprintbtn'];
    if($showbutton==1){
      $bill = 'fm_manager_bill.html';    
    }   
    $oTbs = new clsTinyButStrong();    
    $oTbs->LoadTemplate('templates/'.$lang.'/customer/'.$bill);   
    $oTbs->MergeBlock('blk_list', $arr); 
    $oTbs->Show(TBS_NOTHING);
    $objResponse->addAssign('fmfrmmanager_divprint', 'innerHTML', $oTbs->Source);
    $objResponse->addScript("$('#fmfrmmanager_divprint').dialog('open')"); 
    if($promo_value!=0){
      $objResponse->addScript("$('#fmfrmmanager_trPromotionBill').show()");   
    }else{
      $objResponse->addScript("$('#fmfrmmanager_trPromotionBill').hide()");  
    }
    //  echo $bill_idtemp; die();
    $objResponse->addScript("fm_obj.assignPriceSave('$Room_id','$bill_idtemp')");    
    //$objResponse->addScript("frmmanager_lastTotal=$lastTotal;");
    
    return $objResponse->getXML();
}

 function fmmanager_deleteproduct($Room_id,$pro_id){
    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sql = " delete from cus_history_product$tbl_postfix  where table_id = '$Room_id' and   product_id = '$pro_id' and flg = 0 ";
    $result = $objDbSelect->Execute($sql);
    //echo $sql; die();
    $objResponse->addScript('changeWaiting(1);');
    return $objResponse->getXML();  
 }
 function fmfrmmanager_mergeRoom($tblfrom,$tblto){
    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    
    $sql = " select count(id) as num  from cus_history_product$tbl_postfix  where table_id = '$tblto' and flg = 0 ";
    $result = $objDbSelect->GetArray($sql);
    $count = $result[0]['num'];
    if($count!=0){
        $sql = " update  cus_history_product$tbl_postfix  set table_id = '$tblto'  where table_id = '$tblfrom' and flg = 0 ";
        $result = $objDbSelect->Execute($sql);
        $objResponse->addScript("xajax_fmfrmmanager_loadProduct($tblto);");
        
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Bàn ghép đang trống!');");  
    }
    
    return $objResponse->getXML();  
 }

    
?>